package org.carabiner.infinitest.swingui;

import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

public class WindowBoundsManager extends WindowAdapter
{
  private static final String FRAME_BOUNDS_WIDTH = "frameBounds.width";
  private static final String FRAME_BOUNDS_HEIGHT = "frameBounds.height";
  private static final String FRAME_BOUNDS_X = "frameBounds.x";
  private static final String FRAME_BOUNDS_Y = "frameBounds.y";

  @Override
  public void windowClosing(WindowEvent event)
  {
    JFrame frame = (JFrame) event.getSource();
    File settingsFile = getSettingsFile();
    Properties prop = new Properties();
    Rectangle rect = frame.getBounds();
    prop.setProperty(FRAME_BOUNDS_X, Integer.toString(rect.x));
    prop.setProperty(FRAME_BOUNDS_Y, Integer.toString(rect.y));
    prop.setProperty(FRAME_BOUNDS_WIDTH, Integer.toString(rect.width));
    prop.setProperty(FRAME_BOUNDS_HEIGHT, Integer.toString(rect.height));
    try
    {
      prop.store(new FileOutputStream(settingsFile), "");
    }
    catch (FileNotFoundException e1)
    {
      throw new RuntimeException(e1);
    }
    catch (IOException e)
    {
      throw new RuntimeException(e);
    }
  }

  static File getSettingsFile()
  {
    String userHomeDir = System.getProperty("user.home");
    return new File(userHomeDir + "/.infinitest.settings");
  }

  public static Rectangle getWindowBounds() throws FileNotFoundException, IOException
  {
    if (!getSettingsFile().exists())
      return new Rectangle(0, 0, 480, 120);
    Properties prop = new Properties();
    prop.load(new FileInputStream(getSettingsFile()));
    int x = Integer.parseInt(prop.getProperty(FRAME_BOUNDS_X));
    int y = Integer.parseInt(prop.getProperty(FRAME_BOUNDS_Y));
    int width = Integer.parseInt(prop.getProperty(FRAME_BOUNDS_WIDTH));
    int height = Integer.parseInt(prop.getProperty(FRAME_BOUNDS_HEIGHT));
    return new Rectangle(x, y, width, height);
  }
}
